# -*- coding: utf-8 -*-

import pygame
from pygame.locals import *
from util import *
from sound import play_sound
from image import *
from Tkinter import *
from message import *
import time
import socket
import threading

connect_flag = 0
flag_sent = False
inString = ''
outString = ''


LINES_NUM = 15
pieces_list_black = []
pieces_list_white = []

flag_white = 0
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
white_flag = 0
white_nick = ''
black_nick = ''
nick = ''
number_person = 0


class Chess:
    
    
    def __init__(self, screen):
        global pos_x, pos_y, c_size
        self.screen = screen

    def empty_list(self):
        global pieces_list_black, pieces_list_white, connect_flag, sock
        connect_flag = 0
        pieces_list_black = []
        pieces_list_white = []
        sock.close()
        flag_sent = True
        outString = 'logout#'
        
    def run(self, elapse):
        global connect_flag, sock, nick
        if connect_flag == 0:            
            try:
                a = login_message('127.0.0.1','30000','anonymous')
                HOST, PORT, nick = a.pop()
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.connect((HOST, int(PORT)))
                connect_flag = 1
                # 发送上线认证
                sock.send('login#'+ nick.encode('utf-8'))
                thin = threading.Thread(target = DealIn, args = (sock,))
                thin.start()
                thout = threading.Thread(target = DealOut, args = (sock,))
                thout.start()
                #print HOST, PORT, nick, connect_flag
            except:
                a = message_box('连接失败\n请检查服务器', '连接失败' )
                a.pop()
                return 'menu'
            
        else:
            self.draw()
            for e in pygame.event.get():
                if e.type == QUIT:
                    return 'quit'
                elif e.type == VIDEORESIZE:
                    SCREEN_SIZE = e.size
                    width, height = self.screen.get_size()
                    try:
                        self.screen = pygame.display.set_mode(SCREEN_SIZE, HWSURFACE | SRCALPHA |RESIZABLE, 32)
                    except:
                        self.screen = pygame.display.set_mode((width, height), HWSURFACE | SRCALPHA |RESIZABLE, 32)
                    refresh(self.screen)
                elif e.type == MOUSEBUTTONDOWN:
                    if e.button == 1:
                        self.fresh_input(e.pos)
                    elif e.button == 3:
                        return 'menu'
        return 'chess'

    def fresh_input(self,pos):
        global pieces_list_black, pieces_list_white, flag_sent, outString, flag_white
        w_width, w_height = self.screen.get_size()
        c_size = int(w_height/(LINES_NUM+1))
        pos_x = int((w_width - c_size*LINES_NUM)/2)
        pos_y = int((w_height - c_size*LINES_NUM)/2)
        
        (x, y) = pos 
        x_pos = x - (pos_x - int(c_size/2))
        y_pos = y - (pos_y - int(c_size/2))
        
        if (x_pos >= 0) and (y_pos >= 0):
            new_pos = (int(x_pos/c_size), int(y_pos/c_size))
            #print x_pos, y_pos, new_pos
            if (new_pos in pieces_list_black) or (new_pos in pieces_list_white):
                print 'already in list'
            elif (new_pos[0] <= LINES_NUM) and (new_pos[1] <= LINES_NUM):
                # 标记发送
                flag_sent = True
                outString = 'pos#' + str(new_pos[0])+','+str(new_pos[1])

    def draw(self):
        global pieces_list_black, pieces_list_white, nick, white_nick, black_nick, number_person
        w_width, w_height = self.screen.get_size()
        c_size = int(w_height/(LINES_NUM+1))
        pos_x = int((w_width - c_size*LINES_NUM)/2)
        pos_y = int((w_height - c_size*LINES_NUM)/2)
        self.screen.fill((247,227,200))
        pygame.draw.rect(self.screen, (0,0,0), Rect((pos_x,pos_y), (c_size*LINES_NUM, c_size*LINES_NUM)), 2)

        person_x = int(pos_x/2)
        person_y = int(w_height/2)
        
        if number_person == 1:
            n_width, n_height =  mysize(nick,'s')
            per_x = int((pos_x - n_width)/2)
            #print nick
            if white_flag == 1:
                pygame.draw.circle(self.screen, (0, 0, 0), (person_x,person_y), int(c_size/2-2))
                myprint(self.screen, nick, (per_x,person_y+c_size), 's', (0, 0, 0))
            else:
                pygame.draw.circle(self.screen, (255, 255, 255), (w_width-person_x,person_y), int(c_size/2-2))
                myprint(self.screen, nick, (pos_x+c_size*LINES_NUM+per_x,person_y+c_size), 's', (0, 0, 0))
                #myprint(self.screen, nick, (w_width-person_x,person_y), 'm', (255, 255, 255))
        elif number_person == 2:
            #print white_nick, black_nick
            pygame.draw.circle(self.screen, (0, 0, 0), (person_x,person_y), int(c_size/2-2))
            pygame.draw.circle(self.screen, (255, 255, 255), (w_width-person_x,person_y), int(c_size/2-2))
            
            n_width, n_height =  mysize(white_nick,'s')
            per_x = int((pos_x - n_width)/2)
            myprint(self.screen, white_nick, (per_x,person_y+c_size), 's', (0, 0, 0))            
            n_width, n_height =  mysize(black_nick,'s')
            per_x = int((pos_x - n_width)/2)
            myprint(self.screen, black_nick, (pos_x+c_size*LINES_NUM+per_x,person_y+c_size), 's', (0, 0, 0)) 
		

        for i in range(0, LINES_NUM):
            pygame.draw.line(self.screen, (128,128,128), (pos_x+i*c_size,pos_y), (pos_x+i*c_size,pos_y+c_size*LINES_NUM), 1)
            pygame.draw.line(self.screen, (128,128,128), (pos_x,pos_y+i*c_size), (pos_x+c_size*LINES_NUM,pos_y+i*c_size), 1)
        for p in pieces_list_black:
            pos = (pos_x+int(p[0])*c_size,pos_y+int(p[1])*c_size)
            pygame.draw.circle(self.screen, (0, 0, 0), pos, int(c_size/2-2))
        for p in pieces_list_white:
            pos = (pos_x+int(p[0])*c_size,pos_y+int(p[1])*c_size)
            pygame.draw.circle(self.screen, (255, 255, 255), pos, int(c_size/2-2))



def DealOut(s):
    global nick, outString, flag_sent
    while True:
        if flag_sent:
            s.send(outString)
            print outString
            flag_sent = False
        else :
            time.sleep(0.1)
        
 
def DealIn(s):
    global pieces_list_black, pieces_list_white, LINES_NUM, white_flag, number_person, white_nick, black_nick
    while True:
        try:
            inString = s.recv(1024)
            print inString
            cmd, data = inString.split('#')
            if 'pos' == cmd:
                flag, x, y = map(int, data.split(','))                
                if -1 == flag:
                    pieces_list_white.append((x, y))
                elif 1 == flag:
                    pieces_list_black.append((x, y))
            elif 'login' == cmd:
                print data
                number_person = 1
                if data == -1:
                    white_flag = 1
                else:
                    white_flag = 0
            elif 'nick' == cmd:
                nick1,id1,nick2,id2 = data.split(',')
                number_person = 2
                if id1 == -1:
                    white_nick, black_nick = nick1.decode('utf-8'), nick2.decode('utf-8')
                else:
                    white_nick, black_nick = nick2.decode('utf-8'), nick1.decode('utf-8')
                #print white_nick, black_nick
               
            elif 'win' == cmd:
                print data
		a = message_box( data+'win', '信息提示')
		a.pop()
                flag_sent = True
                a = ask_box('骚年，再来一发？', '信息提示')
                if a.pop():
                    pieces_list_black = []
                    pieces_list_white = []
                    flag_sent = True
                    outString = 'again#'
                else:
                    flag_sent = True
                    outString = 'logout#'
            elif 'message' == cmd:
                print data
                message_box('信息提示', data)

        except:
            break

